<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\LihuaWxuser;
use app\common\model\User;
use fast\Random;
use think\Validate;


/**
 * 微信登录
 *
 * @ApiRoute (/api/weixin)
 */
class Weixin extends Api
{

    protected $noNeedLogin = ['login', 'bindmobile'];
    protected $noNeedRight = ['*'];
    protected $_err   = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    protected function setErr($str = '')
    {
        $this->_err = $str;
    }

    protected function getErr()
    {
        return $this->_err;
    }

    /**
     * 微信登录
     *
     * @ApiMethod  (POST)
     * @ApiReturn  ({"code":0,"msg":"登录成功","time":"1552540994","data":{}})
     */
    public function login()
    {
        //获取json对象
        $wx = $this->request->post();
        if (!$wx) $this->error('非法操作');

        /*$wx = json_decode($rawData, true);
        if (!$wx && json_last_error()) $this->error('非法操作');*/

        $nulluser = [
            'id'       => 0,
            'username' => '',
            'nickname' => '',
            'mobile'   => '',
            'avatar'   => '',
            'score'    => 0,
            'has_pwd'  => 0,
        ];

        $row = LihuaWxuser::get(['unionid' => $wx['unionId']]);
        if ($row) {
            if ($this->auth->isLogin()) {
                LihuaWxuser::update(['user_id' => $this->auth->id], ['id' => $row['id']]);
                $arr = $this->auth->getUserInfo();
            } else {
                if ($row['user_id'] > 0) {
                    $this->auth->direct($row['user_id']);
                    $arr = $this->auth->getUserInfo();
                } else {
                    $arr = array_merge($nulluser, ['wxuser_id' => $row['id']]);
                }
            }
        } else {
            $data = [
                'user_id'  => 0,
                'openid'   => $wx['openId'],
                'unionid'  => $wx['unionId'],
                'nickname' => $wx['nickName'],
                'gender'   => $wx['gender'],
                'province' => $wx['province'],
                'city'     => $wx['city'],
                'avatar'   => $wx['avatarUrl'],
            ];
            if ($this->auth->isLogin()) {
                $data['user_id'] = $this->auth->id;
                $wxuser = LihuaWxuser::create($data);
                $arr = $this->auth->getUserInfo();
            } else {
                $wxuser = LihuaWxuser::create($data);
                $arr = array_merge($nulluser, ['wxuser_id' => (int)$wxuser->id]);
            }
        }

        $this->success('登录成功', ['userinfo' => $arr]);
    }

    /**
     * 绑定手机号
     *
     * @ApiMethod  (POST)
     * @ApiReturn  ({"code":0,"msg":"登录成功","time":"1552540994","data":{}})
     * @ApiParams  (name="wxuser_id", type="int", required=true, description="微信用户表ID")
     * @ApiParams  (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams  (name="captcha", type="string", required=true, description="验证码")
     */
    public function bindmobile()
    {
        $wxuser_id = $this->request->post('wxuser_id', 0);
        $mobile    = $this->request->post('mobile', '');
        $captcha   = $this->request->post('captcha', '');
        if (!is_numeric($wxuser_id) || !$mobile || !$captcha) $this->error('参数错误');

        if (!Validate::regex($mobile, "^1\d{10}$"))   $this->error('手机号格式错误');
        if (!Sms::check($mobile, $captcha, 'login')) $this->error('验证码错误');

        $user = User::get(['mobile' => $mobile]);
        if (!$user) {
            $username = substr(md5($mobile), mt_rand(1,15), 10);
            $ret = $this->auth->register($username, Random::alnum(8), '', $mobile);
            if ($ret) {
                $arr = $this->returnUserInfo($mobile, $wxuser_id);
                if (false === $arr) $this->error($this->getErr());
                $this->success('绑定成功', ['userinfo' => $arr]);
            }
            $this->error('注册出错');
        }

        $cnt = LihuaWxuser::where('user_id', $user->id)->count();
        if ($cnt > 0) $this->error('手机号已被占用');

        $ret = $this->auth->direct($user->id);
        if ($ret) {
            $arr = $this->returnUserInfo($mobile, $wxuser_id);
            if (false === $arr) $this->error($this->getErr());
            $this->success('绑定成功', ['userinfo' => $arr]);
        }

        $this->error($this->auth->getError());
    }

    //返回用户信息
    protected function returnUserInfo($mobile, $wxuser_id)
    {
        Sms::flush($mobile, 'login');
        $wxuser = LihuaWxuser::get($wxuser_id);
        if ($wxuser['user_id'] > 0) {
            $this->setErr('非法操作');
            return false;
        }
        LihuaWxuser::update(['user_id' => $this->auth->id], ['id' => $wxuser_id]);
        User::update(['nickname' => $wxuser['nickname'], 'avatar' => $wxuser['avatar']], ['id' => $this->auth->id]);
        $info = $this->auth->getUserInfo();
        $info['nickname'] = $wxuser['nickname'];
        $info['avatar']   = $wxuser['avatar'];
        return $info;
    }

    /**
     * 解绑微信
     *
     * @ApiMethod  (POST)
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn  ({"code":0,"msg":"OK","time":"1552540994","data":{}})
     */
    public function unbind()
    {
        LihuaWxuser::where('user_id', $this->auth->id)->delete();
        $this->success('OK', ['userinfo' => $this->auth->getUserInfo()]);
    }

}
